package com.ucode.crm.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ucode.crm.dictionary.CrmResultDefineMsg;
import com.ucode.crm.dictionary.ModuleType;
import com.ucode.crm.dictionary.TeamUserPower;
import com.ucode.crm.mapper.BusinessMapper;
import com.ucode.crm.mapper.ContactsMapper;
import com.ucode.crm.mapper.CrmTeamUserMapper;
import com.ucode.crm.mapper.CustomerMapper;
import com.ucode.crm.mapper.OwnerChangeRecordMapper;
import com.ucode.crm.mode.Contacts;
import com.ucode.crm.mode.CrmTeamUser;
import com.ucode.crm.mode.Customer;
import com.ucode.crm.mode.OwnerChangeRecord;
import com.ucode.crm.service.CustomerService;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ContactsMapper contactsMapper;
    @Autowired
    private CrmTeamUserMapper crmTeamUserMapper;
    @Autowired
    private OwnerChangeRecordMapper ownerChangeRecordMapper;
    
    @Override
    @Transactional(rollbackFor=Exception.class)
    public Customer insert(Customer customer) {
        Date now = new Date();
        Long customerId = IdentifyUtils.getDefaultSnowflakeId();
        customer.setId(customerId);
        customer.setCreatedTime(now);
        customer.setUpdatedTime(now);
        customer.setContactsId(IdentifyUtils.getDefaultSnowflakeId());
        
        Contacts contacts = new Contacts();
        contacts.setId(customer.getContactsId());
        contacts.setDc(0);
        contacts.setName(StrUtil.isNotBlank(customer.getCname())?customer.getCname():customer.getName());
        contacts.setMobile(customer.getMobile());
        contacts.setTelephone(customer.getTelephone());
        contacts.setSex(customer.getSex());
        contacts.setBirthday(customer.getBirthday());
        contacts.setCreatedTime(now);
        contacts.setUpdatedTime(now);
        contacts.setCustomerId(customerId);
        contacts.setCreateUserId(customer.getCreateUserId());
        
        if(customerMapper.insert(customer) == 0 || 
                contactsMapper.insert(contacts) == 0){
            throw new UcodeServiceException(ResultCodeEnum.FAILED);
        }
       
        if(customer.getOwnerUserId() != null && !customer.getOwnerUserId().equals(0L)){
            //客户跟进团队
            CrmTeamUser teamUser = new CrmTeamUser(customer.getId(), ModuleType.customer.code, customer.getOwnerUserId(), TeamUserPower.owner.code);
            teamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
            teamUser.setCreatedTime(now);
            teamUser.setUpdatedTime(now);
            if(crmTeamUserMapper.save(teamUser) ==0)
                throw new UcodeServiceException(ResultCodeEnum.FAILED);
        }
          
        return customer;
    }

    @Override
    public int update(Customer customer) {
        int i = customerMapper.update(customer);
        if(i > 0 && customer.getContactsId() != null && !customer.getContactsId().equals(0L)){
            Contacts contacts = new Contacts();
            contacts.setId(customer.getContactsId());
            contacts.setMobile(customer.getMobile());
            contacts.setSex(customer.getSex());
            contacts.setBirthday(customer.getBirthday());
            contactsMapper.update(contacts);
        }
        return i;
    }
    
    @Override
    public int deleteByLogic(Long id) {
        return customerMapper.deleteByLogic(id);
    }
    
    @Override
    public int deletePoolByLogic(Long id) {
        return customerMapper.deletePoolByLogic(id);
    }

    @Override
    public int delete(List<Long> ids) {
        return customerMapper.delete(ids);
    }
    
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int transfer(Long id, Long ownerUserId,Long operatorId) {
        
        Customer customer = customerMapper.findById(id);
        if(customer == null || customer.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        //公海客户不可转移
        if(customer.getOwnerUserId().equals(0L)){
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_transfer_error,customer.getName());
        }
        
        //自己转让给自己
        if(customer.getOwnerUserId().equals(ownerUserId))
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_transfer_itself_error,customer.getName());
        
        Date now = new Date();
        
        //客户负责人变更记录
        OwnerChangeRecord ownerChangeRecord = new OwnerChangeRecord(customer.getId(), ModuleType.customer.code, customer.getOwnerUserId(), ownerUserId, operatorId);
        ownerChangeRecord.setId(IdentifyUtils.getDefaultSnowflakeId());
        ownerChangeRecord.setCreatedTime(now);
        ownerChangeRecord.setUpdatedTime(now);
        ownerChangeRecordMapper.insert(ownerChangeRecord);
        
        CrmTeamUser oldOwneUser = crmTeamUserMapper.find(customer.getId(), ModuleType.customer.code, customer.getOwnerUserId());
        //移除原负责人
        if(oldOwneUser != null){
            crmTeamUserMapper.delete(oldOwneUser.getId());
        }
        
        //客户跟进团队
        CrmTeamUser teamOwnerUser = new CrmTeamUser(customer.getId(), ModuleType.customer.code, ownerUserId, TeamUserPower.owner.code);
        teamOwnerUser.setId(IdentifyUtils.getDefaultSnowflakeId());
        teamOwnerUser.setCreatedTime(now);
        teamOwnerUser.setUpdatedTime(now);
        crmTeamUserMapper.save(teamOwnerUser);
        
        if(customerMapper.transfer(id, ownerUserId,customer.getOwnerUserId()) == 0){
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_transfer_permission_error,customer.getName());
        }
        
        //批量更新联系人负责人
        contactsMapper.updateOwnerUser(id, ownerUserId);
        //批量更新商机
        businessMapper.updateCustomerOwnerUser(id, ownerUserId);
        //批量更新合同
        
        return 1;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int putInPool(Long id, Long operatorId) {
        
        Customer customer = customerMapper.findById(id);
        if(customer == null || customer.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        //已经在公海
        if(customer.getOwnerUserId()== null ||  customer.getOwnerUserId().equals(0L) || customerMapper.putInPool(id) ==0){
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_existed_pool_error,customer.getName());
        }
        
        Date now = new Date();
        //客户负责人变更记录
        OwnerChangeRecord customer_ownerChangeRecord = new OwnerChangeRecord(customer.getId(), ModuleType.customer.code, customer.getOwnerUserId(), 0L, operatorId);
        customer_ownerChangeRecord.setId(IdentifyUtils.getDefaultSnowflakeId());
        customer_ownerChangeRecord.setCreatedTime(now);
        customer_ownerChangeRecord.setUpdatedTime(now);
        ownerChangeRecordMapper.insert(customer_ownerChangeRecord);
        //移除客户跟进团队
        List<CrmTeamUser> customer_followTeamOwnerUsers = crmTeamUserMapper.findList(customer.getId(), ModuleType.customer.code);
        if(CollUtil.isNotEmpty(customer_followTeamOwnerUsers)){
            List<Long> ids = customer_followTeamOwnerUsers.stream().map(m -> m.getId()).distinct().collect(Collectors.toList());
            crmTeamUserMapper.batchDelete(ids);
        }
        
        contactsMapper.clearCustomerOwnerUser(customer.getId());
        
        return 1;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int receive(Long id, Long ownerUserId, Long operatorId) {
        Customer customer = customerMapper.findById(id);
        if(customer == null || customer.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        //不是公海客户不可分配
        if((customer.getOwnerUserId() != null && !customer.getOwnerUserId().equals(0L)) || customerMapper.receive(id, ownerUserId) == 0){
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_receive_error,customer.getName());
        }
        
        Date now = new Date();
        //客户负责人变更记录
        OwnerChangeRecord customer_ownerChangeRecord = new OwnerChangeRecord(customer.getId(), ModuleType.customer.code, customer.getOwnerUserId(), ownerUserId, operatorId);
        customer_ownerChangeRecord.setId(IdentifyUtils.getDefaultSnowflakeId());
        customer_ownerChangeRecord.setCreatedTime(now);
        customer_ownerChangeRecord.setUpdatedTime(now);
        ownerChangeRecordMapper.insert(customer_ownerChangeRecord);
        
        //客户跟进团队
        CrmTeamUser customer_followTeamOwnerUser = new CrmTeamUser(customer.getId(), ModuleType.customer.code, ownerUserId, TeamUserPower.owner.code);
        customer_followTeamOwnerUser.setId(IdentifyUtils.getDefaultSnowflakeId());
        customer_followTeamOwnerUser.setCreatedTime(now);
        customer_followTeamOwnerUser.setUpdatedTime(now);
        crmTeamUserMapper.save(customer_followTeamOwnerUser);
        
        //批量更新联系人负责人
        contactsMapper.updateOwnerUser(id, ownerUserId);
        //批量更新商机
        //批量更新合同
       
        return 1;
    }
    
    @Override
    public int updateLock(Long id, Integer lockStatus) {
        return customerMapper.updateLockStatus(id, lockStatus);
    }
    
    @Override
    public Customer findById(Long id) {
        return customerMapper.findById(id);
    }

    @Override
    public List<Customer> findByIds(List<Long> ids) {
        return customerMapper.findByIds(ids);
    }

    @Override
    public Paginator<Customer> queryPoolPage(String name, String mobile, Integer areaId, Integer level, Integer source, Date startTime, Date endTime,
            int pagesize, int page) {
        
        return null;
    }
    
    public static void main(String[] args) {
        Long OwnerUserId = 0L;
        System.err.println(OwnerUserId.equals(0L));
    }
    
}
